<?php

namespace app\Http\Controllers\API;

use Auth;
use App\User;
use App\Feedback;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;

class UserController extends Controller
{
    /**
     * Get a validator for an incoming registration request.
     *
     * @param array $data
     *
     * @return \Illuminate\Contracts\Validation\Validator
     */
    private function validator(array $data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'email' => 'required|string|email|max:255|unique:users',
            'password' => 'required|string|min:6',
        ]);
    }

    /**
     * Create a new user instance after a valid registration.
     *
     * @return \App\User
     */
    public function register(Request $request)
    {
        $validator = $this->validator($request->all());

        if ($validator->fails()) {
            return response()->json(['code' => 1, 'msg' => $validator->errors()], 200);
        }
        $input = $request->all();
        $input['password'] = bcrypt($input['password']);
        $user = User::create($input);
        $user->token = $user->createToken('AirboxToken')->accessToken;

        return response()->json(['code' => 0, 'user' => $user]);
    }

    /**
     * login api.
     *
     * @return \Illuminate\Http\Response
     */
    public function login(Request $request)
    {
        $input = $request->all();
        if (Auth::attempt(['email' => $input['email'], 'password' => $input['password']])) {
            $user = Auth::user();
            $user->token = $user->createToken('AirboxToken')->accessToken;

            return response()->json(['code' => 0, 'user' => $user]);
        } else {
            return response()->json(['code' => 1, 'msg' => '账号或密码错误']);
        }
    }
    /**
     * detail api.
     *
     * @return \Illuminate\Http\Response
     */
    public function detail()
    {
        $user = Auth::user();

        return response()->json(['code' => 0, 'user' => $user]);
    }

    public function feedback()
    {
        $user = Auth::user();
        $entity = Feedback::create([
            'user_id' => $user->id,
            'content' => request('content')
        ]);

        return response()->json(['code' => 0]);
    }
}
